package com.ruoyi.generator.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.ruoyi.generator.config.GenConfig;
import org.apache.velocity.VelocityContext;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;

/**
 * 模板处理工具类
 * 
 * @author ruoyi
 */
public class VelocityUtils
{
    /** 项目空间路径 */
    private static final String PROJECT_PATH = "main/java";

    /** mybatis空间路径 */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /** 默认上级菜单，系统工具 */
    private static final String DEFAULT_PARENT_MENU_ID = "3";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable)
    {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String packageName = genTable.getPackageName();
        String tplCategory = genTable.getTplCategory();
        String functionName = genTable.getFunctionName();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tplCategory", genTable.getTplCategory());
        velocityContext.put("tableName", genTable.getTableName());
        velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        velocityContext.put("ClassName", genTable.getClassName());
        velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        velocityContext.put("moduleName", genTable.getModuleName());
        velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
        velocityContext.put("businessName", genTable.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", genTable.getFunctionAuthor());
        velocityContext.put("datetime", DateUtils.getDate());
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("importList", getImportList(genTable));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", genTable.getColumns());
        velocityContext.put("table", genTable);
        setMenuVelocityContext(velocityContext, genTable);
        return velocityContext;
    }

    public static void setMenuVelocityContext(VelocityContext context, GenTable genTable)
    {
        String options = genTable.getOptions();
        JSONObject paramsObj = JSONObject.parseObject(options);
        String parentMenuId = getParentMenuId(paramsObj);
        context.put("parentMenuId", parentMenuId);
    }

    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList(String tplCategory)
    {
        List<String> templates = new ArrayList<String>();
        templates.add("vm/api/domain.java.vm");
        templates.add("vm/api/dto.java.vm");
        templates.add("vm/api/service.java.vm");
        templates.add("vm/api/pom.xml.vm");

        templates.add("vm/core/mapper.java.vm");
        templates.add("vm/core/serviceImpl.java.vm");
        templates.add("vm/core/mapper.xml.vm");
        templates.add("vm/core/Application.java.vm");
        templates.add("vm/core/application.yml.vm");
        templates.add("vm/core/application-druid.yml.vm");
        templates.add("vm/core/logback.xml.vm");
        templates.add("vm/core/pom.xml.vm");

        templates.add("vm/web/controller.java.vm");

        templates.add("vm/sql/sql.vm");
        templates.add("vm/js/api.js.vm");
        templates.add("vm/vue/index.vue.vm");
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable)
    {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = genTable.getBusinessName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + moduleName;
        String vuePath = "vue";

        if (template.contains("vm/api/domain.java.vm"))
        {
            fileName = StringUtils.format("{}-api/src/{}/domain/{}.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/api/dto.java.vm"))
        {
            fileName = StringUtils.format("{}-api/src/{}/dto/{}Dto.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/api/service.java.vm"))
        {
            fileName = StringUtils.format("{}-api/src/{}/service/I{}Service.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/api/pom.xml.vm"))
        {
            fileName = StringUtils.format("{}-api/pom.xml", moduleName);
        }
        else if (template.contains("vm/core/mapper.java.vm"))
        {
            fileName = StringUtils.format("{}-core/src/{}/mapper/{}Mapper.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/core/serviceImpl.java.vm"))
        {
            fileName = StringUtils.format("{}-core/src/{}/service/impl/{}ServiceImpl.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/core/mapper.xml.vm"))
        {
            fileName = StringUtils.format("{}-core/src/{}/{}Mapper.xml", moduleName, mybatisPath, className);
        }
        else if (template.contains("vm/core/Application.java.vm"))
        {
            fileName = StringUtils.format("{}-core/src/{}/"+moduleName.substring(0,1).toUpperCase() + moduleName.substring(1)+"Application.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/core/application.yml.vm"))
        {
            fileName = StringUtils.format("{}-core/src/main/resources/application.yml", moduleName);
        }
        else if (template.contains("vm/core/application-druid.yml.vm"))
        {
            fileName = StringUtils.format("{}-core/src/main/resources/application-druid.yml", moduleName);
        }
        else if (template.contains("vm/core/logback.xml.vm"))
        {
            fileName = StringUtils.format("{}-core/src/main/resources/logback.xml", moduleName);
        }
        else if (template.contains("vm/core/pom.xml.vm"))
        {
            fileName = StringUtils.format("{}-core/pom.xml", moduleName);
        }
        else if (template.contains("vm/web/controller.java.vm"))
        {
            fileName = StringUtils.format("{}-web/src/{}/controller/{}Controller.java", moduleName, javaPath, className);
        }
        else if (template.contains("vm/sql/sql.vm"))
        {
            fileName = businessName + "Menu.sql";
        }
        else if (template.contains("vm/js/api.js.vm"))
        {
            fileName = StringUtils.format("{}-ui/src/api/{}/{}.js", vuePath, moduleName, businessName);
        }
        else if (template.contains("vm/vue/index.vue.vm"))
        {
            fileName = StringUtils.format("{}-ui/src/views/{}/{}/index.vue", vuePath, moduleName, businessName);
        }
        return fileName;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName)
    {
        int lastIndex = packageName.lastIndexOf(".");
        String basePackage = StringUtils.substring(packageName, 0, lastIndex);
        return basePackage;
    }

    /**
     * 根据列类型获取导入包
     * 
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTable genTable)
    {
        List<GenTableColumn> columns = genTable.getColumns();
        GenTable subGenTable = genTable.getSubTable();
        HashSet<String> importList = new HashSet<String>();
        if (StringUtils.isNotNull(subGenTable))
        {
            importList.add("java.util.List");
        }
        for (GenTableColumn column : columns)
        {
            if (GenConstants.TYPE_DATE.equals(column.getJavaType()))
            {
                importList.add("java.util.Date");
                importList.add("com.fasterxml.jackson.annotation.JsonFormat");
            }
            else if (GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType()))
            {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName 模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName)
    {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj 生成其他选项
     * @return 上级菜单ID字段
     */
    public static String getParentMenuId(JSONObject paramsObj)
    {
        if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
                && StringUtils.isNotEmpty(paramsObj.getString(GenConstants.PARENT_MENU_ID)))
        {
            return paramsObj.getString(GenConstants.PARENT_MENU_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

}
